﻿@{
	ViewBag.Title = "AJAX long polling";
}

<div class="block center">
    <h2>AJAX long polling Chat</h2>
    <div class="inputBlock center">
        <input type="text" id="msg" />
        <input class="button" id="broadcast" type="button" value="Send" />
        <ul id="messages"></ul>
    </div>
</div>

@section scripts {
	<script type="text/javascript">
		$(document).ready(function () {
			var username = prompt('Please enter a username:');

			$("#broadcast").click(function () {
				$.post('@Url.Action("SendMessage")', { message: $("#msg").val(), username: username });
			});

			var lastCount = 0;
			function poll() {
				$.ajax({
					url: '@Url.Action("GetLatestMessages")', data: { lastCount: lastCount }, success: function (data) {
						console.log(data);
						lastCount = data.count;
						for (message in data.messages) {
							$('#messages').append('<li>' + data.messages[message].username + ': ' + data.messages[message].message + '</li>');
						}
					}, dataType: "json", complete: poll, timeout: 30000, type: 'POST'
				});
			}

			$.ajax({
				url: '@Url.Action("Connect")', success: function (data) {
						console.log(data);
						lastCount = data.count;
						poll();
					}, dataType: "json", type: 'POST'
				});
		});
	</script>
}